package com.hitqz.robot.biz.flow.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONException;
import com.hitqz.robot.biz.flow.domain.common.FailedCodeEnum;
import com.hitqz.robot.biz.flow.domain.common.ResponseResult;
import com.hitqz.robot.biz.flow.domain.constant.FlowConstant;
import com.hitqz.robot.biz.flow.domain.json.xFlowRule.ChainInfo;
import com.hitqz.robot.biz.flow.domain.json.xFlowRule.Edge;
import com.hitqz.robot.biz.flow.domain.json.xFlowRule.Node;
import com.hitqz.robot.biz.flow.service.XFlowService;
import com.hitqz.robot.biz.flow.util.DagParser;
import com.hitqz.robot.biz.flow.domain.dto.SaveRuleDto;
import com.hitqz.robot.biz.flow.domain.json.xFlowRule.XFlowRuleJsonRootBean;
import com.yomahub.liteflow.builder.el.LiteFlowChainELBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wengyx
 * @date 2023/09/08
 */
@Service
@Slf4j
public class XFlowServiceImpl implements XFlowService {

    @Override
    public ResponseResult<?> parseRuleJson(XFlowRuleJsonRootBean dto) {
        List<Node> nodes = dto.getNodes();
        List<Edge> edges = dto.getEdges();
        ChainInfo chainInfo = dto.getChainInfo();
        //校验节点
        if (CollUtil.isEmpty(nodes)) {
            return ResponseResult.fail(FailedCodeEnum.INVALID_GRAPH_DATA);
        }
        if (!DagParser.checkNodes(nodes,edges,chainInfo)) {
            return ResponseResult.fail(FailedCodeEnum.NODE_NODE_UNIQUE);
        }
        //解析规则
        String el;
        try {
            el = DagParser.parseToExpression(nodes, edges, chainInfo.getStartNodeId(), chainInfo.getEndNodeId());
        } catch (JSONException e){
            return ResponseResult.fail(FailedCodeEnum.PARAM_JSON_ERROR);
        }
        log.info("[liteFlow]parse json to el:\n{}",el);
        //校验规则
        if (!LiteFlowChainELBuilder.validate(el)){
            return ResponseResult.fail(FailedCodeEnum.INVALID_EL_RULE);
        }
        return ResponseResult.success(el);
    }

    @Override
    public ResponseResult<?> save(SaveRuleDto dto) {
        String el = dto.getEl();
        String json = dto.getJson();
        if (StrUtil.isBlank(el)) {
            return ResponseResult.fail(FailedCodeEnum.INVALID_EL_DATA);
        }
        if (StrUtil.isBlank(dto.getName())) {
            return ResponseResult.fail(FailedCodeEnum.INVALID_PROJECT_NAME);
        }
        //保存el
        //获取项目路径
        FileUtil.writeUtf8String(el, FlowConstant.FILE_SAVE_PATH+dto.getName()+".txt");
        //保存图像
        FileUtil.writeUtf8String(json, FlowConstant.FILE_SAVE_PATH+dto.getName()+".json");
        return null;
    }

    public static void main(String[] args) {
        String path = System.getProperty("user.dir");
        log.info(path);
    }

}



